﻿#include "loaddialog.h"
#include "ui_loaddialog.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QFileInfo>

static int g_sDataLottieIndex = 0;
LoadDialog::LoadDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoadDialog)
{
    ui->setupUi(this);
    this->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
    setLoadMode();
}

LoadDialog::~LoadDialog()
{
    delete ui;
}

void LoadDialog::setLoadMode(bool fileMode)
{
    if(fileMode) {
        on_radioButton_file_clicked();
    } else {
        on_radioButton_json_clicked();
    }
}

void LoadDialog::on_radioButton_file_clicked()
{
    m_isFileMode = true;
    ui->radioButton_file->setChecked(true);
    ui->radioButton_json->setChecked(false);
    ui->widget_load_file->show();
    ui->widget_json->hide();
    this->adjustSize();
}


void LoadDialog::on_radioButton_json_clicked()
{
    m_isFileMode = false;
    ui->radioButton_file->setChecked(false);
    ui->radioButton_json->setChecked(true);
    ui->widget_load_file->hide();
    ui->widget_json->show();
    this->adjustSize();
}

void LoadDialog::on_pushButton_brower_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(
        this, u8"选择Lottie动画文件", QString(), u8"动画文件 (*.*)");
    if (filePath.isEmpty())
        return;
    ui->lineEdit_file->setText(filePath);
}


void LoadDialog::on_pushButton_ok_clicked()
{
    if(m_isFileMode) {
        QString fileName = ui->lineEdit_file->text();
        QFileInfo fileInfo(fileName);
        if(fileName.isEmpty() ||
            !fileInfo.exists()) {
            QMessageBox::information(this, u8"提示", u8"请选择有效文件");
            return;
        }
        if(!m_lottieWidget->loadFromFile(fileName)) {
            QMessageBox::information(this, u8"提示", u8"无法加载指定文件");
            return;
        }
        m_lottieName = fileInfo.absoluteFilePath();
    } else {
        QString jsonFile = ui->plainTextEdit_load->toPlainText();
        if(jsonFile.isEmpty()) {
            QMessageBox::information(this, u8"提示", u8"请输入数据内容");
            return;
        }
        if(!m_lottieWidget->loadFromData(jsonFile,
            QString(u8"数据动画%1").arg(++g_sDataLottieIndex))) {
            QMessageBox::information(this, u8"提示", u8"无法加载指定文件");
            return;
        }
        m_lottieName = jsonFile;
    }
    accept();
}


void LoadDialog::on_pushButton_cancel_clicked()
{
    reject();
}


